package com.teufandsub.socialproximity.gui;


import java.util.ArrayList;
import java.util.List;

import net.simonvt.numberpicker.NumberPicker;
import net.simonvt.numberpicker.NumberPicker.OnValueChangeListener;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.teufandsub.socialproximity.R;
import com.teufandsub.socialproximity.controller.Constants;
import com.teufandsub.socialproximity.controller.Controller;
import com.teufandsub.socialproximity.logic.Friend;
import com.teufandsub.socialproximity.logic.User;
import com.teufandsub.socialproximity.services.LocationService;

public class ResearchFriendActivity extends SocialProxActivity implements OnClickListener,
												OnSeekBarChangeListener, OnValueChangeListener {

	/* Activity where you'll find new friend
	 * It's the activity where you'll select research criteria */
	private SeekBar distance;
	private NumberPicker nbFrom, nbTo;
	private RadioGroup rg;
	private int sexFilterValue;
	private TextView areaSizeDispayTv;
	
	private final String AREAFILTER_NAME = "area";
	private final String SEXFILTER_NAME = "sex";
	private final String MIN_AGE_FILTER_NAME = "minAge";
	private final String MAX_AGE_FILTER_NAME = "maxAge";
	
	//Size area filter
	private final int LEVEL1 = 500;
	private final int LEVEL2 = 5000;
	private final int LEVEL3 = 100000;
	private final int LEVEL4 = 1000000;
	
	//Response code :
	private final int CODE_RESEARCH_OKAY = 0;
	private final int CODE_SESSION_INVALID = 1;
	private final String RESULT_NAME = "result";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_research_friend);
		
		controller = Controller.getInstance();
		Button searchButton = (Button) findViewById(R.id.search_button);
		searchButton.setOnClickListener(this);
		
		distance = (SeekBar) findViewById(R.id.area_size_seekbar);
		distance.setOnSeekBarChangeListener(this);
		
		nbFrom = (NumberPicker) findViewById(R.id.number_picker_from);
		nbFrom.setFocusable(true);
		nbFrom.setFocusableInTouchMode(true);
		nbFrom.setMinValue(13);
		nbFrom.setMaxValue(100);
		nbFrom.setValue(13);
		nbFrom.setOnValueChangedListener(this);
		
		nbTo = (NumberPicker) findViewById(R.id.number_picker_to);
		nbTo.setFocusable(true);
		nbTo.setFocusableInTouchMode(true);
		nbTo.setMinValue(13);
		nbTo.setMaxValue(100);
		nbTo.setValue(77);
		nbTo.setOnValueChangedListener(this);
		
		rg = (RadioGroup) findViewById(R.id.sex_filter_rg);
		areaSizeDispayTv = (TextView) findViewById(R.id.area_size_display_tv);
		areaSizeDispayTv.setText(formatAreaSize(distance.getProgress(), distance.getMax())+ "m");
	}
	
	@Override
	public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
		switch(picker.getId()){
		case  R.id.number_picker_from:
			if(newVal>=nbTo.getValue()){
				nbTo.setValue(newVal);
			}
			break;
		case R.id.number_picker_to:
			if(newVal<=nbFrom.getValue()){
				nbFrom.setValue(newVal);
			}
			break;
		}
		
	}
	
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		MenuInflater inflater = this.getSupportMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	};
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;
		switch(item.getItemId()){
			case R.id.action_close:
				intent = new Intent(this, IndexActivity.class);
				startActivity(intent);		
				stopService(new Intent(this, LocationService.class));
				moveTaskToBack(true);	
				break;
			case R.id.action_home_button:
				intent = new Intent(this, HomeActivity.class);
				startActivity(intent);
				break;
			case R.id.action_home:
				intent = new Intent(this, HomeActivity.class);
				startActivity(intent);
				break;
			case R.id.action_log_out: 
				controller.disconnect(this);
				break;
			default:;
		}
		return true;
	}
	
	public int formatAreaSize(int value, int max){
		double returnValue = 0;
		double maxValue = max;
		double receivedValue = value;
		
		if(receivedValue < 0.25 * maxValue) {
			returnValue = receivedValue * LEVEL1 / (0.25 * maxValue);
		} else if(receivedValue < 0.5 * maxValue) {
			returnValue = (receivedValue - 0.25 * maxValue) * LEVEL2 / (0.25 * maxValue) + LEVEL1;
		} else if(receivedValue < 0.75 * maxValue) {
			returnValue = (receivedValue - 0.5 * maxValue) * LEVEL3 / (0.25 * maxValue) + LEVEL2;
		} else if(receivedValue < maxValue) {
			returnValue = (receivedValue - 0.75 * maxValue) * LEVEL4 / (0.25 * maxValue) + LEVEL3;
		} else {
			returnValue = LEVEL4 + 1;
		}
		
		return (int) returnValue;
	}
	
	@Override
	public void onClick(View v) {
		
		switch(rg.getCheckedRadioButtonId()){
			case R.id.male_rb: sexFilterValue = User.SEX_MALE;break;
			case R.id.female_rb: sexFilterValue = User.SEX_FEMALE;break;
			case R.id.none_rb: sexFilterValue = User.SEX_UNKNOWN;break;
		}
		
		switch(v.getId()){
			case R.id.search_button:
				AsyncTask<Void, Void, JSONObject> task = new AsyncTask<Void, Void, JSONObject>() {
					
					ProgressDialog dialog;
					
					@Override
					protected void onPreExecute() {
						super.onPreExecute();
						dialog = ProgressDialog.show(ResearchFriendActivity.this, "", getResources().getString(R.string.loading), true);
					}
					
					@Override
					protected JSONObject doInBackground(Void... params) {
						JSONObject filter = new JSONObject();
						int formattedArea = formatAreaSize(distance.getProgress(), distance.getMax());
						try {
							filter.put(AREAFILTER_NAME, formattedArea);
							filter.put(SEXFILTER_NAME, sexFilterValue);
							filter.put(MIN_AGE_FILTER_NAME, nbFrom.getValue());
							filter.put(MAX_AGE_FILTER_NAME, nbTo.getValue());
						} catch (Exception e) {
							Log.e(Constants.APP_NAME, "Error to create JSONObject research : " + e.toString());
							
						}				
						return controller.getConnectedUsers(ResearchFriendActivity.this, filter);
					}
					
					@Override
					protected void onPostExecute(JSONObject result) {
						super.onPostExecute(result);
						dialog.dismiss();
						if(result!=null){
							int code = CODE_SESSION_INVALID;
							try {
								code=result.getInt(Constants.CODE_NAME);
							} catch (Exception e) {
								Log.e(Constants.APP_NAME, "Error to retrieve code during research : " + e.toString());
							}
							
								if(code==CODE_RESEARCH_OKAY){
									JSONArray users=null;
									try {
										users = result.getJSONArray(RESULT_NAME);
									} catch (Exception e) {
										Log.e(Constants.APP_NAME, "Error to retrieve existed user : " + e.toString());
									}
									
									if(users!=null){
										ArrayList<Friend> usersList = new ArrayList<Friend>();
										for(int i=0;i<users.length();i++){
											try {
												usersList.add(new Friend(users.getJSONObject(i)));
											} catch (Exception e) {
												Log.e(Constants.APP_NAME, "Error to retrieve existed user from JSONArray : " + e.toString());
											}	
										}
										controller.setConnectedUserList(usersList);
										Intent it = new Intent(ResearchFriendActivity.this, SearchResultActivity.class);
										startActivity(it);
									}
								}else if(code==CODE_SESSION_INVALID){
									Toast.makeText(ResearchFriendActivity.this, getResources().getString(R.string.invalid_session), Toast.LENGTH_LONG).show();
									Intent it = new Intent(ResearchFriendActivity.this,LoginActivity.class);
									startActivity(it);
								}
						}else{
							Toast.makeText(ResearchFriendActivity.this, getResources().getString(R.string.get_users_error), Toast.LENGTH_LONG).show();
						}
					}
				};
				
				task.execute();
				break;
			default: Log.e(Constants.APP_NAME, "No Action on this view");
		}
		
	}
	
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		int valueToDisplay = formatAreaSize(progress, seekBar.getMax());
		if(valueToDisplay<1000){
			areaSizeDispayTv.setText(valueToDisplay+"m");
		}else if(valueToDisplay<LEVEL4){
			areaSizeDispayTv.setText(valueToDisplay/1000.0+"km");
		}else{
			areaSizeDispayTv.setText(getResources().getString(R.string.unlimited_distance));
		}
		
	}
	
	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		//Nothing to do.
		
	}
	
	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		//Nothing to do.
		
	}
	
}
